<template>
  <div class="channels">
    <!-- <navbar :title="'渠道'"></navbar> -->
    <div class="tabbar">
      <tabs v-model="active" color="#283C79" @change="onTabsChange">
        <tab :title="'直属代理（'+agentsList.total+'）'"></tab>
        <tab :title="'分销商（'+sellersList.total+'）'"></tab>
      </tabs>
    </div>

    <div class="agent-grade" v-if="active == 0">
      <p>代理级别：</p>
      <p class="select-grade" @click="showPopup = true">
        <span>{{selectedAgencyLevel.level_name}}</span>
        <icon name="arrow-down" size="1rem" color="#3F3A40" />
      </p>
    </div>

    <div class="tabs-content">
      <div class="agents-list">
        <list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          v-if="active == 0"
           ref="loadList"
        >
          <div v-for="(item,index) in allList.rows" :key="index" @click="goToAgentDetail(item.id)">
            <agent-item :avatar="item.head_img">
              <div class="agent-info" slot="agent-info">
                <p>
                  <span>姓名：</span>
                  <span>{{item.name}}</span>
                </p>
                <p>
                  <span>级别：</span>
                  <span>{{item.level_name}}</span>
                </p>
                <p>
                  <span>代理编号：</span>
                  <span>{{item.agent_number}}</span>
                </p>
              </div>
            </agent-item>
          </div>
        </list>

        <list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          v-if="active == 1"
           ref="loadList"
        >
          <div v-for="(item,index) in allList.rows" :key="index">
            <agent-item :avatar="item.head_img" :type="'noclick'">
              <div class="agent-info" slot="agent-info">
                <p>
                  <span>姓名：</span>
                  <span>{{item.name}}</span>
                </p>
                <p>
                  <span>级别：</span>
                  <span>{{item.level_name}}</span>
                </p>
                <p>
                  <span>代理编号：</span>
                  <span>{{item.agent_number}}</span>
                </p>
              </div>
            </agent-item>
          </div>
        </list>
      </div>
    </div>
    <popup :show="showPopup" @onCancel="onCancel">
      <div>
        <picker
          @cancel="onCancel"
          value-key="level_name"
          show-toolbar
          :columns="agencyLevelList"
          @confirm="onConfirm"
        />
      </div>
    </popup>
  </div>
</template>

<script>
import { Tab, Tabs, Icon, Picker, List } from "vant";
import agentItem from "../components/agent_item.vue";
import navbar from "../components/navbar.vue";
import popup from "../components/popup.vue";
import http from "../service/myHttp.js";
import urls from "../service/url.js";
import { mapState } from "vuex";
import { defaultAvatar } from "../service/default_source.js";
import { staticHost } from '../service/HOST.js'

export default {
  data() {
    return {
      staticHost: staticHost,
      defaultAvatar: defaultAvatar,
      active: Number(localStorage.getItem("tabbarIndex")) || "0",
      showPopup: false,
      loading: false,
      finished: false,
      pageNumber: 1,
      pageSize: 10,
      uid: "",
      isRefreshing: false,
      isLoading: false,
      isFinished: false,
      httpList: {
        0: urls.HQZSDL,
        1: urls.HQFXS
      },
      selectedAgencyLevel: {
        id: 0,
        level_name: "全部"
      },
      allList: {
        rows: []
      },
      agentsList: {
        total: 0,
        rows: {
          name: "李唐",
          level_name: "T粉",
          agent_number: "1223114",
          head_img: require("../img/我的授权.png")
        }
      },
      sellersList: {
        total: 0,
        rows: {
          name: "李唐",
          level_name: "T粉",
          agent_number: "1223114",
          head_img: require("../img/我的授权.png")
        }
      },
      agencyLevelList: [
        {
          id: 0,
          level_name: "全部"
        }
      ]
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.login_module.userinfo,
      countAlias: "userInfo"
    })
  },
  beforeRouteLeave(to, from, next) {
    if (to.path == "/home/my") {
      localStorage.removeItem("tabbarIndex");
    }
    next()
  },
  components: {
    Icon,
    Tab,
    Tabs,
    agentItem,
    navbar,
    popup,
    Picker,
    List
  },
  async mounted() {
    // 获取代理等级列表
    await this.getAgencyLevel();

    // 获取代理数量
    await this.getAgentList();

    // 获取分销商数量
    await this.getSellerList();
  },
  methods: {
    onTabsChange(index) {
      this.active = index;
      localStorage.setItem("tabbarIndex", this.active);

      this.pageNumber = 1;
      this.allList = { rows: [] };
      this.loading = false;
      this.finished = false;

      setTimeout(() => {
        this.$refs.loadList.check();
      }, 100);
    },
    // 获取代理列表和分销商列表
    async onLoad() {
      let option = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        id: this.userInfo.id,
        tokenId: this.userInfo.id
      };

      if (this.selectedAgencyLevel.id != 0) {
        option = Object.assign({}, option, {
          agencyLevel: this.selectedAgencyLevel.id
        });
      }

      http.post(this.httpList[this.active], option).then(res => {
        if (res.data.code == 200) {
          // console.log(this.allList.rows.concat(res.data.data.rows));
          this.allList.rows = this.allList.rows.concat(res.data.data.rows);
          this.pageNumber++;

          console.log("继续加载");
          // this.finished = true;
          this.loading = false;

          // this.onLoad()
        }
        if (res.data.code == 300) {
          console.log("加载成功");
          this.loading = false;
          this.finished = true;
        }
      });
    },
    // 获取代理数量
    getAgentList() {
      this.pageNumber = 1;
      let option = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        id: this.userInfo.id,
        tokenId: this.userInfo.id
      };

      return http.post(urls.HQZSDL, option).then(res => {
        if (res.data.code == 200) {
          this.agentsList = res.data.data;
          this.pageNumber++;
        }
      });
    },

     // 获取分销商数量
    getSellerList() {
      this.pageNumber = 1;
      let option = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        id: this.userInfo.id,
        tokenId: this.userInfo.id
      };

      return http.post(urls.HQFXS, option).then(res => {
        if (res.data.code == 200) {
          this.sellersList = res.data.data;
          this.pageNumber++;
        }
      });
    },

    // 获取代理等级列表
    getAgencyLevel() {
      return http
        .post(urls.JZDLXLK, {
          id: this.userInfo.id,
          tokenid: this.userInfo.id
        })
        .then(res => {
          if (res.data.code == 200) {
            this.agencyLevelList.push(...res.data.data);
            // this.agencyLevelList.push({ id: 0, level_name: "全部" });
          }
        });
    },
    onCancel() {
      this.showPopup = false;
    },

    // popup点击确定时
    onConfirm(value) {
      this.selectedAgencyLevel = value;
      this.showPopup = false;
      this.pageNumber = 1;
      this.allList = {rows:[]};

      this.loading = false;
      this.finished = false;
    },

    // 跳转到代理详情
    goToAgentDetail(id) {
      this.$router.push({
        path: "/agent_detail",
        query: { id: id || 1 }
      });
    }
  }
};
</script>

<style scoped>
.channels {
  height: 100%;
}

.tabbar{
  position: sticky;
  top: 0;
}

.tabs-content,
.agents-list {
  --height: calc(100% - 48px - 3px);
  height: var(--height);
  /* height: 580px; */
}

.agent-grade {
  margin-top: 1px;
  padding: 10px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.agent-grade > p {
  width: 25%;
}

.select-grade {
  flex: 1;
  height: 80%;
  text-align: left;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgb(234, 234, 234, 0.6);
  border-radius: 5px;
  padding: 3px 10px;
}

.tabs-content {
  margin-top: 5px;
}
</style>